import time
import random
from playwright.sync_api import sync_playwright


class BeedancingCert:
    def __init__(self):
        self.content = ""

    def get_core(self, cert_url, proxy_url=None, proxy_pre=None):
        proxy = None
        if proxy_url:
            if proxy_pre:
                proxy = {
                    "server": proxy_url,
                    "username": proxy_pre.split(":")[0],
                    "password": proxy_pre.split(":")[0]
                }
            else:
                proxy = {
                    "server": proxy_url
                }
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True,
                                        proxy=proxy,
                                        args=[
                                            "--disable-blink-features=AutomationControlled",
                                            "--disable-infobars"
                                        ]
                                        )

            def get_random_user_agent():
                agents = [
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; "
                ]
                return random.choice(agents)

            def stealth_page(context):
                page = context.new_page()
                page.add_init_script("""
                    Object.defineProperty(navigator, 'webdriver', {
                        get: () => undefined
                    })
                """)
                return page
            context = browser.new_context(
                # user_agent=get_random_user_agent(),
                viewport={"width": 1366, "height": 768}
            )
            page = stealth_page(context)

            page.goto(cert_url)
            page.wait_for_selector("img[draggable]")
            time.sleep(random.uniform(1.5, 2.5))
            self.content = page.content()
            browser.close()
        return self.content
